using UnityEngine;

public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                // 场景中查找已有实例
                _instance = FindObjectOfType<T>();
                
                // 没有找到则自动创建
                if (_instance == null)
                {
                    GameObject go = new GameObject(typeof(T).Name + "_Singleton");
                    _instance = go.AddComponent<T>();
                }
            }
            return _instance;
        }
    }

    protected virtual void OnSingletonAwake() { }

    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this as T;
            DontDestroyOnLoad(gameObject); // 跨场景保留
            OnSingletonAwake();
        }
        else
        {
            // 发现重复实例则销毁新实例
            if (_instance != this)
            {
                Destroy(gameObject);
                Debug.LogWarning($"已存在 {typeof(T).Name} 实例，自动销毁重复对象: {gameObject.name}");
            }
        }
    }
    public void OnDestroy()
    {
        if (_instance == this)
        {
            _instance = null;
        }
    }
}